'''
Author: momochong0
Date: 2021-05-24 20:14:59
LastEditors: momochong0
LastEditTime: 2021-05-25 00:02:19
Description: 要推网络荣誉出品
'''
import requests
import re
from lxml import etree
import os
if __name__ == '__main__':
    print('请根据类别代码选择下载的种类')
    print(
        '亚洲人:449,幻想女孩:45821,景观:711,科技:1240,视频游戏:55,性质:37,动漫:1,山脉:328,模式:869,赛博朋克:376,'
    )
    print(
        '动漫女孩:5,分形的:1748,艺术品:323,英雄联盟:537,4K:65348,抽象:74,数字艺术:479,极简主义:2278,幻想艺术:853,源真冲击:95047,更多标签...'
    )
    imglist = []
    headers = headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    }
    url = 'https://wallhaven.cc/'
    page_html = requests.get(url=url, headers=headers).text
    # print(page_html)
    tree = etree.HTML(page_html)
    img_id = tree.xpath('//div[@class="pop-tags"]')
    for Ids in img_id:
        names = Ids.xpath('./span/a/text()')
        imgurls = Ids.xpath('./span/a/@href')
        # print(imgurls)
    for (name, imgurl) in zip(names, imgurls):

        uu = re.compile('&sorting=random&ref=fp')
        aa = uu.sub('', imgurl)
        i = aa.split(':')[-1]
    id = input('请输入你要下载图片类型代码：')
    url = 'https://wallhaven.cc/search?q=id:' + id
    img_html = requests.get(url=url, headers=headers).text
    # print(img_html)
    tree = etree.HTML(img_html)
    Imgurls = tree.xpath('//section[@class="thumb-listing-page"]/ul')

    if not os.path.exists('./' + id):
        os.mkdir('./' + id)

    for imgurls in Imgurls:
        imgurl = imgurls.xpath('./li/figure/img/@data-src')
    for name in imgurl:
        #替换字符串
        uu = re.compile('small')
        ii = uu.sub('full', name)
        cc = re.compile('th')
        img_url = cc.sub('w', ii)

        imgurllist = list(img_url)
        imgurllist.insert(31, 'wallhaven-')
        img_url = ''.join(imgurllist)
        print(img_url)
        img_data = requests.get(url=img_url, headers=headers).content
        img_name = name.split('/')[-1]
        # print(img_name)
        img_path = id + '/' + img_name
        with open(img_path, 'wb') as fp:
            fp.write(img_data)
            print(img_name + '下载成功！')
